package com.zsj.juc.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="https://gitee.com/zhengshengjun">zsj</a>
 * @date 2023/12/5.
 */
@Slf4j
class LTicket {

    private int number = 30;

    //创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    //卖票方法
    public void sale() {
        //上锁
        lock.lock();
        try {
            if (number > 0) {
                log.info(Thread.currentThread().getName() + "卖出第" + number-- + "张票,剩余" + number);
            }
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
@Slf4j
public class LSaleTicket {


    public static void main(String[] args) {
        LTicket t = new LTicket();
        log.info("开始");

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                t.sale();
            }
        }, "aaa").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                t.sale();
            }
        }, "bbb").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                t.sale();
            }
        }, "ccc").start();
        log.info("结束");
    }

}
